//============================================================================
// Name        : Rcall.cpp
// Author      : 
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include "Caller.h"

#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    int c;
    opterr = 0;
    char * InetAddr = NULL;
    int Port = 0;

   while ((c = getopt (argc, argv, "a:p:")) != -1)
    {
		switch (c)
		{
		case 'a':
			if (optarg) InetAddr = optarg;
		break;

		case 'p':
			if (optarg) Port = atoi(optarg);
		break;

		default:
			break;
		}
    }

   if (optind == 1)
    {
		printf("\n"
			  "Rcall [options]\n"
			  "\tRcall is the Cally client.\n"
			  "\tOptions:\n"
			  "\t\t-a  address       dotted string internet address"
			  "\t\t-p  port          port number");
    }

	Caller * CallerInst = new Caller();

	char FunctionName[MAX_NAME_SIZE];
	char Params[MAX_PARAM_SIZE];

	int Res = 0;

	if (InetAddr == NULL)
	{
		InetAddr = "127.0.0.1";
	}

	if ((Res = CallerInst->Initialize(InetAddr, Port)) != CALLER_OK)
	{
		cout << "Caller init error: " << Res << endl;
		return -1;
	}

	while (1)
	{
		// Get the function name
		cout << "Function name (or quit, ls, close): " ;
		cin >> FunctionName;

		if (strcmp("quit", FunctionName) == 0)
		{
			break;
		}

		if (strcmp("ls", FunctionName) == 0)
		{
			char List[MAX_BUFF_SIZE];
			CallerInst->List(List, MAX_BUFF_SIZE);
			cout << List << endl;
			continue;
		}

		if (strcmp("close", FunctionName) == 0)
		{
			CallerInst->Close();
			cout << "Cally closed!" << endl;
			break;
		}

		// Get the params
		cout << "Params: " ;
		cin >> Params;

		// Call
		StatusType Status = OK;
		char Errors[MAX_ERROR_SIZE];
		char Returns[MAX_RETURN_SIZE];
		CallerInst->Call(&Status, FunctionName, Params, Returns, Errors, 0, NULL);
		if (Status == OK)
		{
			printf("%s\n", Returns);
		}

		if (Status == ERROR)
		{
			printf("%s\n", Errors);
		}
	}

	cout << "Bye bye!" << endl;

	CallerInst->Finalize();

	return 0;
}
